import React, { Component } from "react";
import { Checkbox, Select, Table } from "antd";
import { connect } from "dva";
import moment from "moment";
// import { openNotificationWithIcon } from "utils/comm";
import styles from "./index.less";

const { Option } = Select;

const TYPE = {
  WORKING_DAY: "工作日",
  OFF_DAY: "休息日",
};

const isDateConnect = (lastDate, thisDate) => {
  let lastMoment = moment(lastDate.start);
  const thisMoment = moment(thisDate.start);
  if (lastMoment.diff(thisMoment, "d") === -1) {
    return true;
  }

  lastMoment = moment(lastDate.end);
  if (lastMoment.isValid() && lastMoment.diff(thisMoment, "d") === -1) {
    return true;
  }

  return false;
};

@connect(({ weekdaysManagement: { workingDayList, realSpecialDay, selectedYear } }) => ({
  workingDayList, realSpecialDay, selectedYear,
}))
class StepThree extends Component {

  columns = [
    {
      title: "起始日期",
      dataIndex: "start",
      key: "start",
      /* sorter: (a, b) => moment(a.start).diff(moment(b.start), "days"),
       defaultSortOrder: "ascend", */
      render: (text) => text && text.substring(0, 10),
    },
    {
      title: "结束日期",
      dataIndex: "end",
      key: "end",
      render: (text) => text || "--",
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      render: (text) => TYPE[text],
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    },
  ];

  handleChange = (year) => {
    const { selectedYear } = this.props;
    this.getData(moment(selectedYear).year(year));
  };

  getData = (date) => {
    const { dispatch } = this.props;
    dispatch({
      type: "weekdaysManagement/getOffDayList",
      queryMoment: date,
    });
  };

  getSpecialDayList = () => {
    const { realSpecialDay, selectedYear } = this.props;
    return Object.keys(realSpecialDay)
      .sort()
      .filter((date) => date.startsWith(`${moment(selectedYear).year()}`))
      .map((date) => realSpecialDay[date])
      .filter(({ removed }) => !removed);
  };

  getConnectedSpecialDayList = () => {
    return this.getSpecialDayList()
      .reduce((dateList, dateDetail) => {
        if (dateList.length === 0) return [dateDetail];

        const lastDate = dateList[dateList.length - 1];
        if (lastDate.type === dateDetail.type && lastDate.remark === dateDetail.remark) {
          if (isDateConnect(lastDate, dateDetail)) {
            /* 与前一个日期相连，合并 */
            return dateList.slice(0, dateList.length - 1).concat([{
              ...lastDate,
              end: moment(dateDetail.start).format("YYYY-MM-DD"),
            }]);
          }
        }
        return [...dateList, dateDetail];
      }, []);
  };

  getYearOption = () => {
    const year = moment().year();
    const options = [];
    for (let i = year - 10; i < year + 10; i += 1) {
      options.push(
        <Option key={i} value={i}>
          {i}
        </Option>,
      );
    }
    return options;
  };

  render() {
    const { workingDayList = [], selectedYear } = this.props;
    return (
      <div className={styles.root}>
        <div className={styles.panel}>
          <div className={styles.title}>工作日设置：</div>
          <div className={styles.content}>
            <div>
              {
                workingDayList.map((item) => (
                  <Checkbox
                    key={item.code}
                    value={item.code}
                    checked
                    disabled
                  >
                    {item.name}
                  </Checkbox>
                ))
              }
            </div>
          </div>

        </div>
        <div className={styles.panel}>
          <div className={styles.title}>节假日及例外设置：</div>
          <div className={styles.content}>
            <Select
              value={moment(selectedYear).year()}
              style={{ width: 120 }}
              onChange={this.handleChange}
            >
              {this.getYearOption()}
            </Select>
            <Table
              dataSource={this.getConnectedSpecialDayList()}
              columns={this.columns}
              rowKey="start"
              pagination={false}
              scroll={{ y: 380 }}
            />
          </div>
        </div>
      </div>
    );
  }
}

export default StepThree;
